package com.makejl.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

public class HtmlToPdf {

	public static void main(String[] args) {
		HtmlToPdf ih = new HtmlToPdf();
		ih.htmlCodeComeFromFile("E:\\iResume\\test\\csszen.htm",
				"E:\\iResume\\test\\c.pdf");
		// ih.htmlCodeComeString("Hello中文", "E:\\iResume\\test\\main2.pdf");

	}

	public void htmlCodeComeFromFile(String filePath, String pdfPath) {
		Document document = new Document();
		try {

			OutputStream os = new FileOutputStream(pdfPath);

			ITextRenderer render = new ITextRenderer();

			String url = new File(filePath).toURI().toURL().toString();
			// URL ur=new URL("http://www.csszengarden.com/");
			// String url=ur.toString();

			render.setDocument(url);

			ITextFontResolver fontResolver = render.getFontResolver();

			render.layout();
			render.createPDF(os);
			os.close();

			System.out.println("create ok");
			document.close();
			System.out.println("文档创建成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void htmlCodeComeString(String htmlCode, String pdfPath) {
		Document doc = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
			doc.open();
			// 解决中文问题
			BaseFont bfChinese = BaseFont.createFont("STSong-Light",
					"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
			Paragraph t = new Paragraph(htmlCode, FontChinese);
			doc.add(t);
			doc.close();
			System.out.println("文档创建成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}